package com.cloudsea.yunhaiserver.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloudsea.yunhaianalysis.entity.SalesAnalysis;
import com.cloudsea.yunhaianalysis.mapper.SalesAnalysisMapper;
import com.cloudsea.yunhaianalysis.service.WarningService;
import com.cloudsea.yunhaistores.entity.Stores;
import com.cloudsea.yunhaistores.mapper.SkusMapper;
import com.cloudsea.yunhaistores.mapper.StoresMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
public class RealtimeMonitorTask {

    private static final Logger log = LoggerFactory.getLogger(RealtimeMonitorTask.class);

    @Autowired private StringRedisTemplate redisTemplate;
    @Autowired private SalesAnalysisMapper salesAnalysisMapper;
    @Autowired private StoresMapper storesMapper;
    @Autowired private SkusMapper skusMapper;
    @Autowired private WarningService warningService;

    private static final String REALTIME_SALES_KEY_PREFIX = "sales:realtime:";

    @Scheduled(fixedDelayString = "PT10M", initialDelayString = "PT1M") // 每10分钟执行一次
    public void monitorSalesRate() {
        log.info("开始执行【实时销售速率监控】任务...");

        // 1. 获取所有需要监控的门店
        List<Stores> stores = storesMapper.selectList(null); // 实际项目中可能只监控活跃门店

        for (Stores store : stores) {
            // 2. 找到历史相似日 (简化：上周同日)
            LocalDate today = LocalDate.now();
            LocalDate similarDate = today.minusWeeks(1);

            // 3. 查询相似日当天的所有销售记录
            List<SalesAnalysis> historicalSales = salesAnalysisMapper.selectList(
                    new QueryWrapper<SalesAnalysis>().eq("store_id", store.getId()).eq("record_date", similarDate)
            );
            if (historicalSales.isEmpty()) {
                continue; // 没有历史数据，无法对比
            }

            // 4. 计算当前已营业时长
            LocalTime now = LocalTime.now();
            // 简化：假设营业时间从早上8点开始
            long hoursElapsed = Duration.between(LocalTime.of(8, 0), now).toHours();
            if (hoursElapsed <= 0) continue;

            // 5. 遍历历史销售的每个SKU，进行对比
            for (SalesAnalysis historicalSkuSale : historicalSales) {
                // a. 获取历史同期的累计销量
                // (更精确的算法会查询历史当天当前时点前的累计销量，这里简化为总销量)
                double historicalAvgRate = (double) historicalSkuSale.getQuantitySold() / 10; // 假设营业10小时

                // b. 获取今天的实时销量
                String redisKey = REALTIME_SALES_KEY_PREFIX + store.getId() + ":" + historicalSkuSale.getSkuId() + ":" + today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                String realtimeSalesStr = redisTemplate.opsForValue().get(redisKey);
                int realtimeSales = StringUtils.hasText(realtimeSalesStr) ? Integer.parseInt(realtimeSalesStr) : 0;

                double realtimeRate = (double) realtimeSales / hoursElapsed;

                // c. 对比并生成预警
                String skuName = skusMapper.selectById(historicalSkuSale.getSkuId()).getSkuName();
                if (realtimeRate > historicalAvgRate * 2.0) { // 销量超出预期100%
                    String content = String.format("【销量激增预警】[%s] 今日销量远超预期！当前销售速率是同期的 %.1f 倍，请关注库存。", skuName, realtimeRate / historicalAvgRate);
                    warningService.createWarning(store.getId(), "SALES_UNEXPECTEDLY_HIGH", content);
                } else if (realtimeRate < historicalAvgRate * 0.5 && realtimeSales > 0) { // 销量不及预期50%
                    String content = String.format("【销量低迷预警】[%s] 今日销量严重不及预期。当前销售速率仅为同期的 %.1f 倍，建议考虑促销。", skuName, realtimeRate / historicalAvgRate);
                    warningService.createWarning(store.getId(), "SALES_UNEXPECTEDLY_LOW", content);
                }
            }
        }
        log.info("【实时销售速率监控】任务执行完毕。");
    }
}
